<template>
    <div id="main">   



        <!-- //游戏展示部分 -->
        <div class="left-1">
            <div style="position: relative; display: inline-block;" >
            <img :src="'http://47.99.51.143:9000/files/' + game.game_image" alt="游戏图片" fit="scale-down" class="image">
            <i
              
            v-if="game.game_id == 1"
            @click="change(game.id), jinshi(game.game_id)"
           
            class="el-icon-star-on"
            style="position: absolute; top: 5px; right: 5px; font-size: 20px; color: #f90; cursor: pointer;"
          ></i>
          <i
            v-else
            @click="change(game.id), jinshi(game.game_id)"
            alert="取消收藏成功"
            class="el-icon-star-off"
            style="position: absolute; top: 5px; right: 5px; font-size: 20px; color: #f90; cursor: pointer;"
          ></i>

           </div>


            <div class="left-2" >
                <div >游戏名：{{ game.game_name }}</div>
                <div >作者：{{ game.game_author }}</div>
                <div >价格：{{ game.price }}元</div>
                <div >发布时间：{{ game.release_date }}</div>
                <div >简介：{{ game.game_description }}</div>

            </div>

            
            <div   class="left-3">
                <el-button 
                type="primary" 
                size="small" 
                @click="changeShopCarId(game.id), buyNow(game.shopCarId)"
                :style="{ color: game.shopCarId == 1 ? 'white' : 'white', backgroundColor: game.shopCarId == 1 ? '#f56c6c' : '#67c23a' }"
                >
                  {{ game.shopCarId == 1 ? '取消加入购物车' : '加入购物车' }}
                </el-button>


                <el-button type="primary" size="small" 
                style="margin-left:40px"
                
                @click="orderShow = true, addOrder()"
                :disabled="isPurchased"
                >
                {{ isPurchased ? '已购买' : '生成订单' }}</el-button> 


                <el-button type="primary" size="small" @click="change(game.id), jinshi(game.game_id)" 
                style="margin-left: 40px"
                :style="{ color: game.game_id == 1 ? 'white' : 'white', backgroundColor: game.game_id == 1 ? '#f56c6c' : '' }"
                >
                {{ game.game_id == 1 ? '取消收藏' : '加入收藏' }}
              </el-button>  
                


              <!-- 支付表单 -->
      <el-dialog title="支付" :visible.sync="showPaymentDialog" width="30%">
        <div>
          <p>账户余额：￥{{ user.money }}</p>
          <p>需要支付：￥{{ game.price }}</p>
          
        </div>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button type="success" v-if="user.money >= game.price" @click="toPay(user.id),changeIsPurchased(game.id) ">确认支付</el-button> -->
          <el-button type="success" v-if="parseInt(user.money) >= parseInt(game.price)" @click="toPay(user.id), joinshopCar(), topayboss(game.busId)">确认支付</el-button>
          <p v-else>余额不足，请<a href="/recharge">前往充值</a></p>
          <p  v-if="paymentStatus === 'success'" >购买完成！</p>
          <el-button type="danger" @click="showPaymentDialog = false">取消</el-button>
        </span>
      </el-dialog>






     <!--  订单生成界面 -->
     <el-dialog title="订单生成"   :visible.sync="orderShow" width="30%">
      <el-form :model="order" >
        <el-form-item label="商品名称" >
          <el-input v-model="order.goodname" readonly :style="{ color: 'black' }"></el-input>
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input v-model="order.goodId" readonly :style="{ color: 'black' }"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="order.goodprice" readonly :style="{ color: 'black' }"></el-input>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="order.paytype" >
            <el-option label="支付宝" value="1" disabled></el-option>
            <el-option label="微信" value="2" disabled></el-option>
            <el-option label="银行卡" value="3" disabled></el-option>
            <el-option label="余额支付" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="order.goodcategory" readonly :style="{ color: 'black' }"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="order.gooddescription" readonly :style="{ color: 'black' }"></el-input>
        </el-form-item>
        <el-form-item label="订单时间"> 
          <el-input v-model="formattedCreateTime" :readonly="true" :style="{ color: 'black' }"></el-input>
          
        </el-form-item>
        <el-table-column prop="shopstatic" label="是否购买" width="140">
          <template #default="{ row }" >
            {{ row.shopstatic == 1 ? '已购买' : '待支付' }}
          </template>
        </el-table-column>

        <div>

          <el-button @click="orderShow = false">取 消</el-button>
          <el-button type="primary" style="float: right;"  @click="showPaymentDialog = true">去支付</el-button>
        </div>




      </el-form>  
    </el-dialog>























     

            </div>





        </div>






        <!-- //评论部分 -->

        <div  class="comment">  
            
            
        
        <div  class="comment-title" >评论区</div>
        <el-input
          class="comment-input"
          type="textarea"
          placeholder="请输入内容"
          v-model="Comment.comment"
          maxlength="30"
          show-word-limit
        >
        </el-input>
        <el-button type="primary" icon="el-icon-s-promotion" circle @click="submitComment()"></el-button>


        <div   style="max-height: 400px; 
        overflow-y: auto; ">  
          <div v-for="item in thisGameComments" :key="item.id" class="comment-item"  >
            <div style="float: left; width: 20%;background-color:gray;border-radius: 10px; ">
            <el-avatar
                :size=55
                  :src="'http://47.99.51.143:9000/files/' + item.image"></el-avatar>
                  
              <span style="margin-left: 10px; font-size:15px;top:0px;position:relative;color:pink;">{{ item.name }}</span>
            </div>
            <!-- <img :src="comment.image" alt="用户头像"  class="user-avatar"> -->
            <div class="comment-content" style="float: left; ">
              <!-- <h5>{{ comment.name }}</h5> -->
              <p style="background-color: #f5f5f5; color: #333; margin-left: 10px; ">{{ item.comment }}</p>
            </div>
          </div>


        </div>


        </div>
    </div>
    
    
</template>



<script >

import request from '@/request/request.js';
import { EventBus } from '@/main.js';
import moment from "moment";


export default {
  /*  filters: {
   formatDateTime: function(value) {
     if (!value) return '';
     return moment(value).format('YYYY-MM-DD HH:mm:ss'); // 使用moment.js格式化日期时间
   }
 }, */
  data() {
    return {
      game: localStorage.getItem("game") ? JSON.parse(localStorage.getItem("game")) : {},
      shop: localStorage.getItem("shop") ? JSON.parse(localStorage.getItem("shop")) : {},
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      Comment: {
        comment: "",
        gameId: "",
        userId: "",
        name: "",
        image: ""
      },
      Games: {},
      thisGameComments: [],
      orderShow: false,
      order: {},
      showPaymentDialog: false,
      shopstatus: {},
      usermoney: 0,
      paymentStatus: '',



    }
  },


  methods: {
    changeIsPurchased(id) {
      request.get("/games/change/purchased/" + id).then((res) => {
        if (res.code === "0") {
          this.changeOrder(id);
          this.$message.success({ message: "购买成功", type: "success" });
        } else {
          this.$message({ message: "购买失败", type: "error" });
        }
      });

    },
    changeOrder(id) {
      request.get("/order/change/purchased/" + id).then((res) => {
        if (res.code === "0") {
          this.message.success({ message: "购买成功", type: "success" });
        }
      });

    },

    topayboss(id) {
      request.get("/user/" + id).then((res) => {
        if (res.code === "0") {
          this.usermoney = this.user.money;
        }
      });
      const money = parseInt(this.usermoney) + parseInt(this.game.price);
      request.put(`/user/${id}/pay?money=${money}`).then((res) => {
        if (res.code === "0") {
          this.$message.success({ message: "支付成功", type: "success" });
        } else {
          this.$message({ message: "支付失败", type: "error" });
        }
      });

    },
    toPay(id) {
      const money = this.user.money - this.game.price;
      request.put(`/user/${id}/pay?money=${money}`).then((res) => {
        if (res.code === "0") {
          this.paymentStatus = 'success';
          this.showPaymentDialog = false;
          this.orderShow = false;
          this.selectUser(id);
          this.$message.success({ message: "支付成功", type: "success" });
          window.location.reload();
        } else {
          this.$message({ message: "支付失败", type: "error" });
        }
      });
    },
    selectUser(id) {
      request.get("/user/" + id).then((res) => {
        if (res.code === "0") {
          this.user = { ...this.user, ...res.data };
          localStorage.setItem("user", JSON.stringify(this.user));
        }
      });
    },
    submitComment() {

      this.Comment.gameId = this.game.id;
      this.Comment.userId = this.user.id;
      this.Comment.name = this.user.name;
      this.Comment.image = this.user.image;
      request.post("/comment/add", this.Comment).then((res) => {
        if (res.code === "0") {
          this.$message({ message: "评论成功", type: "success" });
          this.Comment.comment = "";
          this.getComments();
        } else {
          this.$message({ message: "评论失败", type: "error" });
        }
      });
    },
    getComments() {
      request.get("/comment/" + this.game.id).then((res) => {
        if (res.code === "0") {
          this.thisGameComments = res.data;
          console.log(this.thisGameComments);

        }
      });
    },

    change(id) {
      request.get("/games/change/" + id).then((res) => {
        if (res.code === "0") {
          /* this.$message.success({ message: "收藏成功", type: "success" }); */
          /* this.game.game_id = res.data.game_id; */
          this.selectGame(id);

        } else {
          /* this.$message({ message: "收藏失败", type: "error" }); */
        }
      });
    },
    jinshi(id) {
      if (id == 0) {
        this.$message({ message: "已将该游戏收藏", type: "success" });
      } else {
        this.$message({ message: "取消收藏成功", type: "error" });
      }
    },
    selectGame(id) {
      request.get("/games/" + id).then(res => {
        console.log(res.data);
        if (res.code === "0") {
          /* this.Games = res.data; */

          /* this.game.game_id = res.data; */
          this.game = { ...this.game, ...res.data };
          localStorage.setItem("game", JSON.stringify(this.game));
          /*   localStorage.setItem("game", JSON.stringify(res.data)); */
          /*  location.reload(); */
        }

      });
    },
    changeShopCarId(id) {
      request.get("/games/change/cart/" + id).then((res) => {
        if (res.code === "0") {

          this.selectGame(this.game.id)
          this.game = { ...this.game, ...res.data };
          localStorage.setItem("game", JSON.stringify(this.game));
          EventBus.$emit('reloadSide');
        }
      });
    },
    joinshopCar() {
      this.Games.game_name = this.game.game_name;
      this.Games.game_image = this.game.game_image;
      this.Games.price = this.game.price;
      this.Games.gameId = this.game.id;
      this.Games.userId = this.user.id;
      this.Games.game_description = this.game.game_description;
      this.Games.category = this.game.category;
      this.Games.release_date = this.game.release_date;
      this.Games.is_purchased = 1;
      this.Games.busId = this.game.busId;
      this.Games.url = this.game.url;
      request.post("/shop/add", this.Games).then((res) => {
        if (res.code === "0") {
          this.changeOrder(this.game.id);
        }
      });
    },
    buyNow(id) {
      if (id == 0) {

        this.$message({ message: "该游戏已加入购物车", type: "success" });
      } else {

        this.$message({ message: "已将该游戏移除购物车", type: "error" });
      }
    },
    getOrder(id) {
      request.get("/order/" + id).then((res) => {
        if (res.code === "0") {
          this.order = res.data;
          console.log(this.order);
        }
      });
    },
    changeOrderstatic(id) {
      request.get("/order/change/static/" + id).then((res) => {
        if (res.code === "0") {
          this.$message.success({ message: "订单状态更新成功", type: "success" });

        }
      });
    },


    addOrder() {
      /*   this.selectGame(id); */
      this.order.goodname = this.game.game_name;
      this.order.goodprice = this.game.price;
      this.order.shopstatic = 0;
      this.order.gooddescription = this.game.game_description;

      this.order.goodcategory = this.game.category;
      this.order.gameId = this.game.id;
      this.order.userId = this.user.id;
      this.order.paytype = 4;
      this.order.goodId = Math.random().toString(36).substr(2, 9);
      this.order.busId = this.game.busId;
      this.order.username = this.user.name;
      request.post("/order/add", this.order).then((res) => {
        if (res.code === "0") {
          this.$message.success({ message: "订单生成成功", type: "success" });
          this.getOrder(this.order.id);

        } else {
          this.$message({ message: "订单生成失败", type: "error" });
        }
      });
    },
    /* searchshopgame(id){
      request.get("/shop/search/"+id).then((res) => {
        if (res.code === "0") {
          this.shopstatus=res.data;}
        });
      }, */
    /* updateshop(userId,gameId){
      request.get(`/shop/purchased?userId=${userId}&gameId=${gameId}`).then(res => {
        if (res.code === "0") {
            this.shop = {...this.shop, ...res.data};
            localStorage.setItem("shop", JSON.stringify(this.shop));
        } else {
            this.$message.error('获取游戏列表失败');
        }
    }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('网络错误或服务器不可达');
     
  });
    }, */


    selectshop(userId, gameId) {

      request.get(`/shop/purchased?userId=${userId}&gameId=${gameId}`).then(res => {
        /* this.shop = {...this.shop, ...res.data};
            localStorage.setItem("shop", JSON.stringify(this.shop)); */

        /* localStorage.setItem("shop", JSON.stringify(res.data)); */
        if (res.code === "0") {
          this.shop = res.data;  // 更新响应式属性
          localStorage.setItem("shop", JSON.stringify(res.data));
        } else {
          this.$message.error('获取游戏列表失败');
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('网络错误或服务器不可达');

      });
    },
  },

  created() {
    this.getComments();
    this.selectshop(this.user.id, this.game.id);
    console.log(this.order.createtime);
    /*   this.searchshopgame(this.user.id); */
  },
  computed: {
    isPurchased() {
      return this.shop;
    },
    formattedCreateTime() {
      return moment(this.order.createtime).format('YYYY-MM-DD HH:mm:ss');
    }
  }


}
</script>




<style scoped>
#main {
  width: 100%;

  height: 100%;
  border: 1px solid #ccc;
  border-radius: 10px;


}

.left-1 {
  width: 48%;
  height: 100%;
  float: left;
  border: 1px solid #ccc;
  border-radius: 10px;
}

.left-2 {
  float: left;
  width: 60%;
  background-image: url("/src/views/photo/yun4.webp");
  margin: 30px 0 0 10px;
  height: 170px;
  font-size: 20px;
  font-weight: bold;
  border-radius: 10px;
  color: rgb(0, 0, 0);
}

.left-3 {
  float: left;
  width: 80%;
  margin: 40px 0 0 30px;

}

.image {
  width: 200px;
  float: left;
  display: block;
  height: 200px;
  margin-left: 30px;


}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.comment {

  width: 50%;
  height: 100%;
  float: right;
  border: 1px solid #ccc;
  border-radius: 10px;
  background-color: #339aca;
}

.comment-title {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin: 20px 0px 5px 10px;
  background-color: transparent;
  width: 25%;
}

.comment-input {
  width: 70%;
  height: auto;
  margin: 5px 10px 10px 10px;
}

.comment-item {

  border: 1px solid white;
  float: left;
  width: 100%;
  background-color: #f5f5f5;
  border-radius: 10px;
}
</style>











